<template>
  <div class="page-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>分类管理</span>
          <el-button type="primary" size="small" @click="openCreateDialog">新增分类</el-button>
        </div>
      </template>

      <!-- 分类表格 -->
      <el-table
        :data="categories"
        style="width: 100%"
        border
        stripe
        height="100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" min-width="200" />
        <el-table-column prop="sortOrder" label="排序" width="100" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" type="warning" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="fetchCategories"
        class="pagination"
      />
    </el-card>

    <!-- 新增 / 编辑弹窗 -->
    <el-dialog
      :title="isEdit ? '编辑分类' : '新增分类'"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCategoryPage,
  createCategory,
  updateCategory,
  deleteCategory
} from '@/api/admin'

/* 列表数据 */
const categories = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

/* 弹窗 */
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const form = reactive({ id: null, name: '', sortOrder: 0 })

/* 校验规则 */
const rules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
})

/* 获取分页 */
const fetchCategories = async () => {
  const res = await getCategoryPage(currentPage.value, pageSize.value)
  categories.value = res.data.data.list ?? res.data.data.records ?? []
  total.value = res.data.data.list.length
}

/* 打开新增 */
const openCreateDialog = () => {
  isEdit.value = false
  Object.assign(form, { id: null, name: '', sortOrder: 0 })
  nextTick(() => formRef.value?.resetFields())
  dialogVisible.value = true
}

/* 打开编辑 */
const openEditDialog = (row) => {
  isEdit.value = true
  Object.assign(form, row)
  nextTick(() => formRef.value?.clearValidate())
  dialogVisible.value = true
}

/* 提交 */
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (isEdit.value) {
        await updateCategory(form.id, { name: form.name, sortOrder: form.sortOrder })
        ElMessage.success('更新成功')
      } else {
        await createCategory({ name: form.name, sortOrder: form.sortOrder })
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      fetchCategories()
    } catch (e) {
      ElMessage.error('操作失败')
    }
  })
}

/* 删除 */
const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该分类吗？', '提示', {
    type: 'warning'
  })
    .then(async () => {
      await deleteCategory(id)
      ElMessage.success('删除成功')
      fetchCategories()
    })
    .catch(() => {})
}

/* 初始化 */
fetchCategories()
</script>

<style lang="scss" scoped>
.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.box-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 12px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}
</style>
